<script setup lang="ts">
import { ref, inject } from 'vue'
import regexUtil from '../../util/RegexUtil'
import captchaData from '../../data/CaptchaData'
import LoginLeft from '../../components/LoginLeft.vue'
import { setPassword } from '../../util/SessionUtil'
import { db } from '../../db/db'
import $ from 'jquery'
import 'bootstrap/dist/js/bootstrap'
import { useRouter } from 'vue-router'

const router = useRouter()

const form = ref({
    usersTypeId: '',
    phoneNumber: '',
    code: '',
    password: '',
    okPassword: ''
})
const formErr = ref({
    usersTypeId: false,
    phoneNumber: false,
    code: false,
    password: false,
    okPassword: false
})
const formMsg = ref({
    usersTypeId: '',
    phoneNumber: '',
    code: '',
    password: '',
    okPassword: ''
})

const axios: any = inject('axios')

const verificationCode = ref('验证码')
const verificationCodeBtnState = ref(false)

const isCheck = ref(false)

let randomVc = 0

const count = 120 //间隔函数，1秒执行
let curCount = 0 //当前剩余秒数
let interValObj: any
function obtainCode() {
    if (!checkPhoneNumber()) {
        return
    } else {
        randomVc = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000

        axios
            .post('/overt/system/sms/verification-code', {
                token: 'bezG5CJQ8DDm',
                phoneNumber: form.value.phoneNumber,
                code: randomVc
            })
            .then(function (response: any) {
                if (response.data.state) {
                    curCount = count
                    //设置button效果，开始计时
                    verificationCodeBtnState.value = true
                    verificationCode.value = curCount + '秒'
                    interValObj = window.setInterval(setRemainTime, 1000)
                }
            })
            .catch(function (error: any) {
                console.log(error)
            })
    }

}

function setRemainTime() {
    if (curCount === 0) {
        window.clearInterval(interValObj) //停止计时器
        verificationCodeBtnState.value = false
        verificationCode.value = '验证码'
    } else {
        curCount--
        verificationCode.value = curCount + '秒'
    }
}

function checkUsersTypeId() {
    formErr.value.usersTypeId = false
    formMsg.value.usersTypeId = ''
    if (form.value.usersTypeId === '') {
        formErr.value.usersTypeId = true
        formMsg.value.usersTypeId = '请选择用户类型'
        return false
    }
    return true
}

async function checkPhoneNumber() {
    formErr.value.phoneNumber = false
    formMsg.value.phoneNumber = ''
    if (form.value.phoneNumber === '') {
        formErr.value.phoneNumber = true
        formMsg.value.phoneNumber = '手机号不能为空'
        return false
    } else {
        if (!regexUtil.mobile.test(form.value.phoneNumber)) {
            formErr.value.phoneNumber = true
            formMsg.value.phoneNumber = '手机号11位数字'
            return false
        }

        if (Number(form.value.usersTypeId) == 4) {
            // 学生
            const tempStu = await db.student.where('phoneNumber').equals(form.value.phoneNumber).toArray()

            if (tempStu.length <= 0) {
                formErr.value.phoneNumber = true
                formMsg.value.phoneNumber = '未查询到手机号对应用户信息'
                return false
            }
        } else if (Number(form.value.usersTypeId) == 3) {
            // 组织
            const tempOr = await db.organize.where('responsiblePersonPhoneNumber').equals(form.value.phoneNumber).toArray()

            if (tempOr.length <= 0) {
                formErr.value.phoneNumber = true
                formMsg.value.phoneNumber = '未查询到手机号对应用户信息'
                return false
            }
        } else {
            formErr.value.phoneNumber = true
            formMsg.value.phoneNumber = '根据用户类型未查询到手机号对应用户信息'
            return false
        }

    }
    return true
}

function checkCode() {
    formErr.value.code = false
    formMsg.value.code = ''
    if (form.value.code === '') {
        formErr.value.code = true
        formMsg.value.code = '验证码不能为空'
        return false
    } else {
        // if (captchaData.indexOf(form.value.code) < 0) {
        if (randomVc != Number(form.value.code)) {
            formErr.value.code = true
            formMsg.value.code = '验证码错误'
            return false
        }
    }
    return true
}

function checkPassword() {
    formErr.value.password = false
    formMsg.value.password = ''
    if (form.value.password === '') {
        formErr.value.password = true
        formMsg.value.password = '密码不能为空'
        return false
    } else {
        if (!regexUtil.password.test(form.value.password)) {
            formErr.value.password = true
            formMsg.value.password = '密码为6~20位字母,数字及特殊字符'
            return false
        }
    }
    return true
}

function checkOkPassword() {
    formErr.value.okPassword = false
    formMsg.value.okPassword = ''
    if (form.value.okPassword === '') {
        formErr.value.okPassword = true
        formMsg.value.okPassword = '确认密码不能为空'
        return false
    } else {
        if (!regexUtil.password.test(form.value.okPassword)) {
            formErr.value.okPassword = true
            formMsg.value.okPassword = '密码为6~20位字母,数字及特殊字符'
            return false
        }

        if (form.value.password != form.value.okPassword) {
            formErr.value.okPassword = true
            formMsg.value.okPassword = '密码不相同'
            return false
        }
    }
    return true
}

// Submit function
const submitCheckForm = () => {
    if (!checkUsersTypeId()) {
        return false
    }

    if (!checkPhoneNumber()) {
        return false
    }

    if (!checkCode()) {
        return false
    }

    isCheck.value = true
}

const submitForm = async () => {

    if (!checkPassword()) {
        return false
    }

    if (!checkOkPassword()) {
        return false
    }

    if (Number(form.value.usersTypeId) == 4) {
        // 学生
        const tempStu = await db.student.where('phoneNumber').equals(form.value.phoneNumber).toArray()

        if (tempStu.length <= 0) {
            formErr.value.phoneNumber = true
            formMsg.value.phoneNumber = '未查询到手机号对应用户信息'
            return false
        }

        db.users.where('username').equals(tempStu[0].username).modify({ password: form.value.password })

        setPassword(form.value.password)
    } else if (Number(form.value.usersTypeId) == 3) {
        // 组织
        const tempOr = await db.organize.where('responsiblePersonPhoneNumber').equals(form.value.phoneNumber).toArray()

        if (tempOr.length <= 0) {
            formErr.value.phoneNumber = true
            formMsg.value.phoneNumber = '未查询到手机号对应用户信息'
            return false
        }

        db.users.where('username').equals(tempOr[0].username).modify({ password: form.value.password })

        setPassword(form.value.password)
    }

    $('#successModal').modal('show')

}

const toLogin = () => {
    $('#successModal').modal('hide')
    router.push({ path: '/web/login' })
}
</script>

<template>
    <!-- Main -->
    <div class="d-md-flex h-md-100 align-items-center">
        <LoginLeft />
        <div class="col-md-6 p-0 bg-white h-md-100 loginarea">
            <div class="d-md-flex align-items-center h-md-100 p-5 justify-content-center">
                <form class="border rounded p-5" @submit.prevent="submitCheckForm" v-if="!isCheck">
                    <h3 class="mb-4 text-center">忘记密码</h3>
                    <div class="form-group">
                        <select class="form-control" :class="formErr.usersTypeId ? 'is-invalid' : ''"
                            v-model="form.usersTypeId" @change="checkUsersTypeId">
                            <option value="">请选择用户类型</option>
                            <option value="4">学生用户</option>
                            <option value="3">组织/商家</option>
                        </select>
                        <div class="invalid-feedback">
                            {{ formMsg.usersTypeId }}
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group is-invalid">
                            <input type="text" class="form-control" :class="formErr.phoneNumber ? 'is-invalid' : ''"
                                v-model.trim="form.phoneNumber" placeholder="手机号" @blur="checkPhoneNumber" />
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" @click="obtainCode"
                                    :disabled="verificationCodeBtnState">
                                    {{ verificationCode }}
                                </button>
                            </div>
                        </div>
                        <div class="invalid-feedback" style="display: block">
                            {{ formMsg.phoneNumber }}
                        </div>
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" :class="formErr.code ? 'is-invalid' : ''"
                            v-model.trim="form.code" placeholder="验证码" @blur="checkCode" />
                        <div class="invalid-feedback">
                            {{ formMsg.code }}
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success btn-round btn-block shadow-sm">验 证</button>
                    <small class="d-block mt-4 text-center">
                        <RouterLink to="/web/login">去登录</RouterLink>
                    </small>
                </form>
                <form class="border rounded p-5" @submit.prevent="submitForm" v-if="isCheck">
                    <h3 class="mb-4 text-center">忘记密码</h3>
                    <div class="form-group">
                        <input type="password" class="form-control" :class="formErr.password ? 'is-invalid' : ''"
                            v-model.trim="form.password" placeholder="新密码" @blur="checkPassword" />
                        <div class="invalid-feedback">
                            {{ formMsg.password }}
                        </div>
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control" :class="formErr.okPassword ? 'is-invalid' : ''"
                            v-model.trim="form.okPassword" placeholder="确认密码" @blur="checkOkPassword" />
                        <div class="invalid-feedback">
                            {{ formMsg.okPassword }}
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success btn-round btn-block shadow-sm">确认修改</button>
                    <small class="d-block mt-4 text-center">
                        <RouterLink to="/web/login">去登录</RouterLink>
                    </small>
                </form>
            </div>
        </div>
    </div>
    <!-- End Main -->

    <!-- Modal -->
    <div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true"
        style="z-index: 9000;">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-success" id="successModalLabel">密码修改成功</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    您好，您的密码已修改成功！
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" @click="toLogin">去登录</button>
                </div>
            </div>
        </div>
    </div>
</template>
